package com.course.httpclient.cookies;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class TestGetCookies {
    private String url;
    private ResourceBundle bundle;
    private CookieStore cookieStore;

    @BeforeTest
    public void beforTest(){
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url =bundle.getString("test.url");
    }

    @Test
    public void getCookies() throws IOException {
        String result;
        String cookiesUrl = this.url+bundle.getString("getcookies");
        HttpGet get = new HttpGet(cookiesUrl);
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
    }
    @Test
    public void getCookies1() throws IOException {
        //拼接url
        String cookiesUrl = this.url+bundle.getString("getcookies");

        //创建请求方法
        HttpGet get = new HttpGet(cookiesUrl);

        //创建cookiesStore存储cookies
        this.cookieStore = new BasicCookieStore();

        //创建带有cookies的httpclient
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        //发送请求
        client.execute(get);

        //获取cookies
        List<Cookie> cookiesList = this.cookieStore.getCookies();
        for(Cookie cookie:cookiesList){
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            System.out.println("cookies name:"+cookieName+"\n"+"cookies value:"+cookieValue);
        }
    }

    //创建cookies以来方法
    @Test(dependsOnMethods = "getCookies1")
    public void useCookies() throws IOException {
        String cookiesUrl = this.url+bundle.getString("usecookies");
        HttpGet get = new HttpGet(cookiesUrl);

        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        HttpResponse response = client.execute(get);

        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode == 200) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(result);
        }
    }
}
